<style scoped lang="scss">
.image-preview {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.9);
  z-index: 9999;
  display: flex;
  align-items: center;
  justify-content: center;
}

.preview-wrapper {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

.preview-image {
  max-width: 90%;
  max-height: 90%;
  object-fit: contain;
}

.page-indicator {
  position: absolute;
  top: 20px;
  color: #fff;
  font-size: 14px;
}

.close-btn {
  position: absolute;
  top: 20px;
  right: 20px;
  color: #fff;
  font-size: 24px;
  background: transparent;
  border: none;
}
</style>
<template>
  <div v-show="isShow" class="image-preview" @click.self="closePreview">
    <!-- 图片容器：支持左右滑动 -->
    <div class="preview-wrapper" @touchstart="handleTouchStart" @touchmove="handleTouchMove" @touchend="handleTouchEnd">
      <img v-for="(img, idx) in images" :key="idx" :src="img" class="preview-image" :style="{
        transform: `translateX(${-(currentIndex * 100)}%)`,
        transition: isTransition ? 'transform 0.3s ease' : 'none'
      }" />
    </div>

    <!-- 页码指示器 -->
    <div class="page-indicator">
      {{ currentIndex + 1 }} / {{ images.length }}
    </div>

    <!-- 关闭按钮（可选） -->
    <button class="close-btn" @click="closePreview">×</button>
  </div>
</template>
<script>
export default {
  name: 'ImagePreview',
  props: {
    images: {
      type: Array,
      required: true,
    },
    defaultIndex: {
      type: Number,
      default: 0,
    },
  },
  data() {
    return {
      isShow: false,
      currentIndex: this.defaultIndex,
      startX: 0,    // 触摸起始X坐标
      moveX: 0,     // 触摸移动X坐标
      isTransition: true, // 是否启用过渡动画
    };
  },
  methods: {
    handleTouchStart(e) {
      this.startX = e.touches[0].clientX;
      this.isTransition = false; // 滑动时关闭过渡，避免卡顿
    },
    handleTouchMove(e) {
      if (!this.startX) return;
      this.moveX = e.touches[0].clientX;
    },
    handleTouchEnd() {
      const deltaX = this.moveX - this.startX;
      const threshold = 50; // 滑动阈值（可调整）

      // 右滑：上一张
      if (deltaX > threshold && this.currentIndex > 0) {
        this.currentIndex--;
      }
      // 左滑：下一张
      else if (deltaX < -threshold && this.currentIndex < this.images.length - 1) {
        this.currentIndex++;
      }

      this.startX = 0;
      this.moveX = 0;
      this.isTransition = true; // 切换后恢复过渡
    },
    // 打开预览
    openPreview(index = 0) {
      this.isShow = true;
      this.currentIndex = index;
      document.body.style.overflow = 'hidden'; // 防止背景滚动
    },
    // 关闭预览
    closePreview() {
      this.isShow = false;
      document.body.style.overflow = '';
      this.$emit('close');
    },
  },
};
</script>
